import HeaderComponent from "@/components/HeaderComponent/HeaderComponent";

import { Input, Toast, PickerView, Picker } from "antd-mobile";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "react-router-dom";

import {
  getNodeArea,
  upgrade,
  upgradeEnum,
  getGoodsList,
} from "@/api/module/user";
import { getApiToken } from "@/api/module/U2U";
import { CenterPopupComponent } from "@/components/CenterPopupComponent/CenterPopupComponent";
import { useAppSelector } from "@/hooks/useAppSelector";
const Step1Component = () => {
  const { t } = useTranslation();
  const [recommend, setrecommend] = useState("");
  const [position, setPosition] = useState("");
  const [secondPassword, setSecondPassword] = useState("");
  const [googleCode, setGoogleCode] = useState("");
  const [upgradeInfo, setUpgradeInfo] = useState<
    Awaited<ReturnType<typeof upgrade>>["data"]
  >({
    get_coin: 0,
    next_level: "",
    price: 0,
    price_jhb: 0,
    price_zcb: 0,
  });
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  const [params] = useSearchParams();
  useEffect(() => {
    if (!userInfo || !userInfo.parent_id) return; // 确保 userInfo 存在
    // requpgrade(upgradeEnum.check);
    goodsList();
    reqNodeArea();
  }, [params]);
  // 获取升级商品
  const [nextLevel, setNextLevel] = useState([]);
  const [visible1, setVisible1] = useState(false);
  const [pickerValue, setPickerValue] = useState<(string | null)[]>();
  const [selectedId, setSelectedId] = useState<number>();
  // 打开弹框的函数
  const handleOpenModal = () => {
    setVisible1(true);
  };
  const goodsList = async () => {
    const res = await getGoodsList();
    if (res.code === 0) {
      setNextLevel(res.data.list_data);
      // 更新 upgradeInfo 状态
      setUpgradeInfo((prevState) => ({
        ...prevState,
        get_coin: res.data.list_data[0]?.get_coin || 0, // 默认取第一个商品的 get_coin
        next_level: res.data.list_data[0]?.title || "", // 默认取第一个商品的 title
        price: res.data.list_data[0]?.price || 0, // 默认取第一个商品的 price
        price_jhb: res.data.list_data[0]?.price_currency_two || 0, // 默认取第一个商品的 price_jhb
        price_zcb: res.data.list_data[0]?.price_currency_one || 0, // 默认取第一个商品的 price_zcb
      }));
    }
  };
  // 构造Picker的columns，假设nextLevel每个元素都有`name`字段
  const typeColumns = [
    nextLevel.map((item) => ({
      label: item.title, // 显示名称，假设字段是 `name`
      value: item.goods_id, // 使用id作为值
      price: item.price,
      price_zcb: item.price_currency_one,
      price_jhb: item.price_currency_two,
      get_coin: item.get_coin,
    })),
  ];
  // 处理Picker确认后的选中值
  const handlePickerConfirm = (v, extend) => {
    setPickerValue(v); // 更新Picker选中的值

    // 假设你需要将选中的商品id设置到 upgradeInfo 的 next_level
    const selectedId = v[0]; // 选中的商品id
    const selectedLevel = extend.items[0].label; //选中的商品等级
    const get_coin = extend.items[0].get_coin;
    const price = extend.items[0].price;
    const price_jhb = extend.items[0].price_jhb;
    const price_zcb = extend.items[0].price_zcb;
    setSelectedId(selectedId);
    // 更新 upgradeInfo 中的 next_level
    setUpgradeInfo((prevState) => ({
      ...prevState,
      get_coin: get_coin,
      next_level: selectedLevel,
      price: price,
      price_jhb: price_jhb,
      price_zcb: price_zcb,
    }));

    console.log("选中的商品ID:", selectedId);
  };

  const reqNodeArea = async () => {
    const id = params.get("id") || "";
    const res = await getNodeArea(userInfo.parent_id);
    if (res.code === 0) {
      setPosition(res.data);
      // setrecommend(id);
    }
  };
  const requpgrade = async (type: upgradeEnum) => {
    if (visible) setVisible(false);
    const res = await upgrade({
      action: type,
      node_user_id: recommend,
      password: secondPassword,
      google_code: googleCode,
      APITOKEN: APIToken,
      goods_id: selectedId || "10001",
    });
    if (type == upgradeEnum.check && res.code === 0) {
      return;
    }
    APIToken && setAPIToken("");
    Toast.show({
      content: res.msg,
    });
    if (res.code == 0) {
      setGoogleCode("");
      setSecondPassword("");
    }
  };
  const [visible, setVisible] = useState(false);
  const [APIToken, setAPIToken] = useState("");
  const reqApiToken = async () => {
    try {
      // || !googleCode
      if (!secondPassword) {
        Toast.show({
          content: t("enterCompleteInformation"),
        });
        return;
      }
      if (!APIToken) {
        const res = await getApiToken();
        setAPIToken(res.data.api_token);
      }
      setVisible(true);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <>
      <div
        className="mt-4 pb-8"
        style={{
          fontSize: "95%",
        }}
      >
        <div
          className="tips text-font-2 text-center mb-8
      "
        >
          {t("pleaseEnter")}
        </div>
        <div className="recommend mt-4">
          <div>{t("reference")}</div>

          <Input
            readOnly
            style={{
              "--font-size": "14px",
              "--color": "#fff",
            }}
            className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
            placeholder={`${t("enter")}`}
            value={userInfo.parent_id}
            onChange={(val) => {
              setrecommend(val);
            }}
          />
        </div>
        <div className="recommend mt-4">
          <div>{t("recommend")}</div>
          <Input
            style={{
              "--font-size": "14px",
              "--color": "#fff",
            }}
            className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
            placeholder={`${t("enter")}`}
            value={recommend}
            onChange={(val) => {
              setrecommend(val);
            }}
          />
        </div>
        <div className="USDT mt-4">
          <div>{t("position")}</div>
          <Input
            readOnly
            style={{
              "--font-size": "14px",
              "--color": "#fff",
            }}
            className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
            placeholder={`${t("enter")}`}
            value={position}
            onChange={(val) => {
              setPosition(val);
            }}
          />
          <div className="mt-2 opacity-50 text-xs">
            <span>{t("willPlaced")}</span>
          </div>
        </div>
        {Object.keys(upgradeInfo).length > 0 &&
          Object.keys(upgradeInfo).map((key) => {
            return (
              <div
                key={key}
                className="flex justify-between items-center mt-4 bg-bg-1 py-4 px-3 rounded-lg"
              >
                {/* <div>{t(key)}</div> */}
                {key != "next_level" && <div>{t(key)}</div>}
                {key == "next_level" && (
                  <div>
                    {t(key)}
                    <span style={{ "font-size": "10px" }}>
                      （{t("optional")}）
                    </span>
                  </div>
                )}
                <div>
                  {key != "next_level" &&
                    upgradeInfo[key as keyof typeof upgradeInfo]}
                  {key == "price" ? "USDT" : ""}
                  {key == "next_level" && (
                    <div onClick={handleOpenModal}>
                      {upgradeInfo[key as keyof typeof upgradeInfo]}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        <Picker
          cancelText={t("cancel")}
          confirmText={t("confirm")}
          style={{
            // @ts-ignore
            "--adm-color-background": "#242424",
          }}
          className="text-white-1 bg-bg-1"
          columns={typeColumns}
          visible={visible1}
          onClose={() => {
            setVisible1(false);
          }}
          value={pickerValue}
          onConfirm={handlePickerConfirm}
        />
        {/* <div className="secondaryPassword mt-4">
          <div>{t("googleCode")}</div>
          <Input
            type="password"
            style={{
              "--font-size": "14px",
              "--color": "#fff",
            }}
            className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
            placeholder={`${t("enter")}`}
            value={googleCode}
            onChange={(val) => {
              setGoogleCode(val);
            }}
          />
        </div> */}
        <div className="secondaryPassword mt-4">
          <div>{t("secondaryPassword")}</div>
          <Input
            type="password"
            style={{
              "--font-size": "14px",
              "--color": "#fff",
            }}
            className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
            placeholder={`${t("enter")}`}
            value={secondPassword}
            onChange={(val) => {
              setSecondPassword(val);
            }}
          />
        </div>
        <div
          onClick={reqApiToken}
          className="mt-6 bg-bg-16 py-4 rounded-md text-center text-base"
        >
          {t("confirm")}
        </div>
      </div>
      {/* <Popup
        visible={visible}
        style={{
          // @ts-ignore
          '--background-color': '#242424',
        }}
        onMaskClick={() => {
          setVisible(false);
        }}
        onClose={() => {
          setVisible(false);
        }}
      >
        <div className="bg-bg-1 text-white-1 h-full px-4 py-6">
          <div className="text-center">{t('pleaseChoosePlacementAccount')}</div>
          <div className="mt-4">
            {accountList.map((item, index) => {
              return (
                <div
                  onClick={() => {
                    setActive(index);
                    setSimuDou(item);
                  }}
                  className="bg-black-1 p-5 mb-3 flex items-center"
                >
                  <Image
                    width={18}
                    src={`${active == index ? getAssetsFile('active.png') : getAssetsFile('Inactive.png')}`}
                  />
                  <span
                    className={`ml-2 ${active == index ? 'text-font-2' : 'text-white-1'}`}
                  >
                    {item}
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      </Popup> */}
      <CenterPopupComponent
        visible={visible}
        setVisible={setVisible}
        title="placementAccount"
        content={`${t("willPlaced")}：${recommend}`}
        onClick={() => requpgrade(upgradeEnum.buy)}
      />
    </>
  );
};
export default function PlacementAccount() {
  return (
    <div className="text-white-1 px-4">
      <HeaderComponent title="placementAccount" />
      <Step1Component />
    </div>
  );
}
